#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

#define NUM sizeof(fd_set) * 8
const int gdefaultfd = -1;

// 最开始的时候,我们的服务器,只有一个文件描述符
class SelectServer
{
public:
    SelectServer(int port) : _port(port),
                             _listen_socket(std::make_unique<TcpSocket>()),
                             _isrunning(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocket(_port);
        for (int i = 0; i < NUM; i++)
        {
            _fd_array[i] = gdefaultfd;
        }
        // 添加listensockfd到数组
        _fd_array[0] = _listen_socket->Fd();
    }
    void Start()
    {
        fd_set rfds; // 读文件描述符集
        _isrunning = true;
        while (_isrunning)
        {
            // 1.清空rfds
            FD_ZERO(&rfds);
            struct timeval timeout = {10, 0};
            int maxfd = gdefaultfd;

            // 2.将_fd_array添加到rfds中
            for (int i = 0; i < NUM; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                {
                    continue;
                }
                FD_SET(_fd_array[i], &rfds);
                // 更新最大值
                if (maxfd < _fd_array[i])
                {
                    maxfd = _fd_array[i];
                }
            }

            // 我们不能让accept来阻塞检测新连接到来,应该让select来负责进行就绪事件的检测
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // 有事件就绪了
                std::cout << "有事件就绪了..., timeout: " << timeout.tv_sec << ":"
                          << timeout.tv_usec << std::endl;
                // rfds: 内核告诉用户,你关心的rfds中的fd,有哪些已经就绪了
                HandlerEvents(rfds);

                break;
            }
        }
        _isrunning = false;
    }
    void HandlerEvents(fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefaultfd)
            {
                continue;
            }
            if (_fd_array[i] == _listen_socket->Fd())
            {
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                    InetAddr client;
                    // listensockfd就绪了! 再获取新连接
                    int newfd = _listen_socket->Accepter(&client);
                    // 这里进行accept不会被阻塞了,因为我们是被select叫来的,只执行拷贝
                    if (newfd < 0)
                    {
                        return;
                    }
                    else
                    {
                        std::cout << "获取了一个新的连接: " << newfd << " client info: " << client.Addr() << std::endl;
                        // 添加新的newfd
                        int pos = -1;
                        for (int j = 0; j < NUM; j++)
                        {
                            if (_fd_array[j] == gdefaultfd)
                            {
                                pos = j;
                                break;
                            }
                        }
                        if (pos == -1)
                        {
                            LOG(LogLevel::ERROR) << "服务器已经满了...";
                            close(newfd);
                        }
                        else
                        {
                            _fd_array[pos] = newfd;
                        }
                    }
                }
            }
            else
            {
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                    char buffer[1024];
                    ssize_t n = recv(_fd_array[i],buffer,sizeof(buffer)-1,0);
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        std::cout << "client# " <<buffer << std::endl;
                        std::string message = "echo# ";
                        message += buffer;
                        send(_fd_array[i],message.c_str(),message.size(),0);
                    }
                    else if(n == 0)
                    {
                        LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << _fd_array[i];
                        close(_fd_array[i]);
                        _fd_array[i] = gdefaultfd;
                    }
                    else
                    {
                        LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << _fd_array[i];
                        close(_fd_array[i]);
                        _fd_array[i] = gdefaultfd;
                    }
                }
            }
        }
    }
    ~SelectServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    int _fd_array[NUM]; // 辅助数组
};
